package com.yhp.util;

import java.sql.*;
import java.util.List;

/**
 * @author 13371
 */
public class DbUtils {
    //1.定义需要的工具类对象
    protected Connection connection = null;
    protected PreparedStatement pps = null;
    protected ResultSet rs = null;
    protected int k = 0;//受影响的行数
    private String url = "jdbc:mysql://localhost:3306/kaikeba?serverTimezone=UTC";
    private String username = "root";
    private String password = "root";

    //2.加载驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //3.获得连接
    protected Connection getConnection() {
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //4.创建通道
    protected PreparedStatement getPps(String sql) {
        try {
            getConnection();//insert into users values(?,?,?,?,)
            pps = connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return pps;
    }

    //5.给占位符赋值 list中保存的是给占位符所赋的值
    private void setParams(List list) {
        try {
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    pps.setObject(i + 1, list.get(i));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    protected int update(String sql, List params) {
        try {
            getPps(sql);
            setParams(params);
            k = pps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return k;
    }

    //7.查询的时候调取一个方法
    protected ResultSet query(String sql, List list) {
        try {
            getPps(sql);
            setParams(list);
            rs = pps.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //8.关闭资源
    protected void closeall() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pps != null) {
                pps.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
